import { createRouter, createWebHistory } from "vue-router";
import { qiankunWindow } from "vite-plugin-qiankun/dist/helper";
import { getAccessToken } from "@/utils/auth";
import {routes} from './routes'
import { useMenuWithOut } from "@/store/modules/useMenu";
const { wsCache } = useCache();
const menuStore = useMenuWithOut()

const router = createRouter({
	history: createWebHistory(qiankunWindow.__POWERED_BY_QIANKUN__ ? `/${import.meta.env.VITE_APP_NAME}` : "/"),
	strict: true,
	routes,
	scrollBehavior: () => ({ left: 0, top: 0 })
});

// 路由加载前
router.beforeEach(async (to, from, next) => {
	const isMain = wsCache.get("isMain");
	if (!isMain) {
		if (getAccessToken()) {
			const is404 = to.matched?.filter(item => item.name !== '404');
			if (['/', '/login'].includes(to.path) || !is404.length) {
				next({ path: "/customer/0" });
			} else {
				next();
			}
		} else {
			if (to.path === "/login") {
				next();
			} else {
				next(`/login`);
			}
		}
	} else {
		next();
	}
	menuStore.setRouteCache(to);
});

export default router;
